import {cache} from './tools';
import * as CacheKeys from '../constants/cache-keys';

const noAuthRoutes = ['Login','Register','Forget','NotFound']

let _token = '';

let auth = {
  init(router) {
    _token = cache(CacheKeys.TOKEN);

    router.beforeEach((to, from, next) => {

      if (to.name === 'Login' && _token) {
        next({
          path: '/'
        })
        return;
      }

      if (!_token && !noAuthRoutes.includes(to.name)) {
        next({
          path: '/login',
          query: {
            redirect: to.fullPath,
          }
        })
        return;
      }

      next();
    })
  },
  getToken() {
    return _token;
  },
  setToken(token) {
    _token = token;
    cache(CacheKeys.TOKEN, token);
  },
  clearToken() {
    _token = '';
    cache(CacheKeys.TOKEN, null)
  }
}

export default auth;
